<template>
  <div class="merchant-edit-container">
    <el-card class="merchant-edit-card">
      <template #header>
        <div class="card-header">
          <span>{{ isEdit ? '编辑商户' : '新增商户' }}</span>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="120px"
        class="merchant-form"
      >
        <!-- 基本信息 -->
        <el-divider content-position="left">基本信息</el-divider>
        <el-form-item label="商户名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入商户名称" />
        </el-form-item>

        <el-form-item label="商户类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择商户类型">
            <el-option label="个人商户" value="personal" />
            <el-option label="企业商户" value="enterprise" />
          </el-select>
        </el-form-item>

        <el-form-item label="联系人" prop="contact">
          <el-input v-model="form.contact" placeholder="请输入联系人姓名" />
        </el-form-item>

        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系电话" />
        </el-form-item>

        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入电子邮箱" />
        </el-form-item>

        <!-- 资质信息 -->
        <el-divider content-position="left">资质信息</el-divider>
        <el-form-item label="营业执照" prop="license">
          <el-upload
            class="license-uploader"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleLicenseSuccess"
            :before-upload="beforeLicenseUpload"
          >
            <img v-if="form.license" :src="form.license" class="license-image" />
            <el-icon v-else class="license-uploader-icon"><Plus /></el-icon>
          </el-upload>
          <div class="upload-tip">支持jpg、png格式，大小不超过2MB</div>
        </el-form-item>

        <el-form-item label="经营地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入经营地址" />
        </el-form-item>

        <el-form-item label="经营范围" prop="businessScope">
          <el-input
            v-model="form.businessScope"
            type="textarea"
            :rows="3"
            placeholder="请输入经营范围"
          />
        </el-form-item>

        <!-- 账户信息 -->
        <el-divider content-position="left">账户信息</el-divider>
        <el-form-item label="登录账号" prop="username">
          <el-input v-model="form.username" placeholder="请输入登录账号" />
        </el-form-item>

        <el-form-item label="登录密码" prop="password" v-if="!isEdit">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="请输入登录密码"
            show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword" v-if="!isEdit">
          <el-input
            v-model="form.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>

        <!-- 其他信息 -->
        <el-divider content-position="left">其他信息</el-divider>
        <el-form-item label="商户状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="active">正常</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            保存
          </el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { getMerchantDetail, updateMerchant, addMerchant } from '@/api/merchant'
import { getToken } from '@/utils/auth'

const route = useRoute()
const router = useRouter()
const formRef = ref(null)
const loading = ref(false)

const isEdit = computed(() => !!route.params.id)

// 上传相关配置
const uploadUrl = import.meta.env.VITE_APP_BASE_API + '/merchant/upload'
const uploadHeaders = {
  Authorization: 'Bearer ' + getToken()
}

const form = reactive({
  name: '',
  type: '',
  contact: '',
  phone: '',
  email: '',
  license: '',
  address: '',
  businessScope: '',
  username: '',
  password: '',
  confirmPassword: '',
  status: 'active',
  remark: ''
})

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (form.confirmPassword !== '') {
      formRef.value?.validateField('confirmPassword')
    }
    callback()
  }
}

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== form.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const rules = {
  name: [
    { required: true, message: '请输入商户名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择商户类型', trigger: 'change' }
  ],
  contact: [
    { required: true, message: '请输入联系人', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入电子邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  license: [
    { required: true, message: '请上传营业执照', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入经营地址', trigger: 'blur' }
  ],
  businessScope: [
    { required: true, message: '请输入经营范围', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入登录账号', trigger: 'blur' },
    { min: 4, max: 20, message: '长度在 4 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: !isEdit.value, validator: validatePass, trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: !isEdit.value, validator: validatePass2, trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择商户状态', trigger: 'change' }
  ]
}

// 获取商户详情
const getDetail = async (id) => {
  try {
    loading.value = true
    const res = await getMerchantDetail(id)
    Object.assign(form, res.data)
  } catch (error) {
    console.error('获取商户详情失败:', error)
    ElMessage.error('获取商户详情失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    const submitData = { ...form }
    if (isEdit.value) {
      delete submitData.password
      delete submitData.confirmPassword
      await updateMerchant(route.params.id, submitData)
      ElMessage.success('更新成功')
    } else {
      await addMerchant(submitData)
      ElMessage.success('创建成功')
    }
    
    router.push('/merchant/list')
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(error.message || '提交失败')
  } finally {
    loading.value = false
  }
}

// 取消
const handleCancel = () => {
  router.back()
}

// 上传相关方法
const beforeLicenseUpload = (file) => {
  const isJPG = file.type === 'image/jpeg'
  const isPNG = file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG && !isPNG) {
    ElMessage.error('上传图片只能是 JPG 或 PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleLicenseSuccess = (res) => {
  if (res.code === 200) {
    form.license = res.data.url
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(res.message || '上传失败')
  }
}

onMounted(() => {
  if (isEdit.value) {
    getDetail(route.params.id)
  }
})
</script>

<style scoped>
.merchant-edit-container {
  padding: 20px;
}

.merchant-edit-card {
  max-width: 1000px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.merchant-form {
  margin-top: 20px;
}

.license-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.license-uploader:hover {
  border-color: #409eff;
}

.license-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.license-image {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.upload-tip {
  font-size: 12px;
  color: #606266;
  margin-top: 5px;
}

:deep(.el-divider__text) {
  font-size: 16px;
  font-weight: bold;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style> 